import axios from "axios";
import { Loading, Message } from "element-ui";
// import store from "@/store";
// import { getToken } from "@/utils/auth";
import qs from "qs";
// import { getZipDownloadUrl, getUploadImageUrl } from "@/api/upload";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: "/", // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout,
});
// 在全局请求和响应拦截器中添加请求状态
let loading = null;
// request interceptor
service.interceptors.request.use(
  (config) => {
    loading = Loading.service({ text: "拼命加载中" });
    NProgress.start();
    // do something before request is sent
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (loading) {
      loading.close();
      NProgress.done();
    }
    return response.data;
  },
  (error) => {
    const errorResponse = error.response;
    if (errorResponse) {
      // console.log(errorResponse);
      if (errorResponse.status === 401) {
        Message.closeAll();
        Message({
          message: "授权已过期，请重新登录",
          type: "error",
          duration: 3 * 1000,
        });
        // } else if (errorResponse.status === 511) {
        // } else if (errorResponse.status === 508) {
        // } else {
        // Message.closeAll();
        // Message({
        //   message: errorResponse.data.error || "Error",
        //   type: "error",
        //   duration: 3 * 1000
        // });
      }
    }
    // 请求超时或者网络有问题
    if (error.message.includes("timeout")) {
      Message.error("请求超时！请检查网络是否正常");
    } else {
      Message.error("请求失败，请检查网络是否已连接");
    }
    return Promise.reject(error);
  }
);

function request(url, data, method) {
  switch (method) {
    case "get":
      return service({
        method: "get",
        url,
        params: data,
      });
    case "delete":
      return service({
        method: "delete",
        url,
        params: data,
      });
    case "put":
      return service({
        method: "put",
        url,
        data: qs.stringify(data),
      });
    case "post":
      return service({
        method: "post",
        url,
        data: qs.stringify(data),
      });
    default:
      return service;
  }
}

export default request;
